package com.starlight.easybuyprictice.filter;

import com.google.code.kaptcha.Constants;
import com.starlight.easybuyprictice.service.Result;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author yfy2001
 * @date 2022/11/28 20:43
 */
public class LoginPostFilter implements Filter {
    //private static final Logger logger = Logger.getLogger(LoginPostFilter.class);
    String captchaFieldName = "captcha";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (RequestMethod.POST.name().equals(((HttpServletRequest) servletRequest).getMethod())){
            String requestCaptcha = ((HttpServletRequest) servletRequest).getHeader(captchaFieldName);
            String genCaptcha = (String)((HttpServletRequest) servletRequest).getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            System.out.println("开始校验验证码，生成的验证码为:" + genCaptcha +"，输入的验证码为:"+requestCaptcha);
            //logger.info("开始校验验证码，生成的验证码为:"+ genCaptcha + "，输入的验证码为:" +requestCaptcha);
            if (!requestCaptcha.equals(genCaptcha)){
                System.out.println("验证码错误。");
                showInterceptionInfo((HttpServletResponse) servletResponse,-1,null,null);
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
    private void showInterceptionInfo(HttpServletResponse response,int status,String msg, Object data){
        Result result=new Result();
        result.setStatus(status);
        result.setMsg(msg);
        result.setData(data);
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader( "Content-Type",
                    "application/json; charset=UTF-8");
            out = response.getWriter();
            out.write(JSONObject.fromObject(result).toString());
        }catch (IOException ie) {
            ie.printStackTrace();
        }finally {
            if (out != null) {
                out.close();
            }
        }
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
